package com.jhgsys.internal.peccancy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.jhgsys.internal.base.entity.BaseUserScoreRecord;
import com.jhgsys.internal.base.service.IBaseUserScoreRecordService;
import com.jhgsys.internal.common.entity.FebsConstant;
import com.jhgsys.internal.common.exception.FebsException;
import com.jhgsys.internal.common.utils.BeanHelper;
import com.jhgsys.internal.common.utils.DateUtil;
import com.jhgsys.internal.peccancy.constant.PeccancyConstant;
import com.jhgsys.internal.peccancy.dto.PeccancyInformationDto;
import com.jhgsys.internal.peccancy.dto.PeccancyInformationQueryDto;
import com.jhgsys.internal.peccancy.entity.PeccancyAuditRecord;
import com.jhgsys.internal.peccancy.entity.PeccancyInformation;
import com.jhgsys.internal.peccancy.entity.PeccancyInformationFile;
import com.jhgsys.internal.peccancy.entity.PeccancyModuleConfig;
import com.jhgsys.internal.peccancy.mapper.PeccancyInformationMapper;
import com.jhgsys.internal.peccancy.service.IPeccancyAuditRecordService;
import com.jhgsys.internal.peccancy.service.IPeccancyInformationFileService;
import com.jhgsys.internal.peccancy.service.IPeccancyInformationService;
import com.jhgsys.internal.common.entity.QueryRequest;
import com.jhgsys.internal.common.utils.FebsUtil;
import com.jhgsys.internal.peccancy.service.IPeccancyModuleConfigService;
import com.jhgsys.internal.system.entity.Dept;
import com.jhgsys.internal.system.entity.Tenant;
import com.jhgsys.internal.system.entity.User;
import com.jhgsys.internal.system.service.IDeptService;
import com.jhgsys.internal.system.service.ITenantService;
import com.jhgsys.internal.system.service.IUserService;
import com.jhgsys.internal.workflow.entity.WorkflowApply;
import com.jhgsys.internal.workflow.entity.WorkflowInfo;
import com.jhgsys.internal.workflow.service.IWorkflowApplyService;
import com.jhgsys.internal.workflow.service.IWorkflowInfoService;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.annotation.Propagation;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.toolkit.StringPool;

import java.util.*;

/**
 * 违章登记 Service实现
 *
 * @author wanghw
 * @date 2024-08-12 09:46:29
 */
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class PeccancyInformationServiceImpl extends ServiceImpl<PeccancyInformationMapper, PeccancyInformation> implements IPeccancyInformationService {

    @Autowired
    private ITenantService tenantService;

    @Autowired
    private IDeptService deptService;


    @Autowired
    private IPeccancyInformationFileService peccancyInformationFileService;

    @Autowired
    private IUserService userService;

    @Autowired
    private IBaseUserScoreRecordService baseUserScoreRecordService;

    @Autowired
    private IPeccancyAuditRecordService auditRecordService;

    @Autowired
    private IPeccancyModuleConfigService peccancyModuleConfigService;

    @Autowired
    private IWorkflowApplyService workflowApplyService;

    @Autowired
    private IWorkflowInfoService workflowInfoService;

    /**
     * 查询（分页）
     * @author wanghw
     * @date 2024-08-12 09:46:29
     * @param request QueryRequest
     * @param peccancyInformation peccancyInformation
     * @return IPage<PeccancyInformation>
    */
    @Override
    public IPage<PeccancyInformation> findPeccancyInformationPage(QueryRequest request, PeccancyInformationQueryDto peccancyInformation) {
        LambdaQueryWrapper<PeccancyInformation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PeccancyInformation::getDeletedFlg, FebsConstant.VALID);
        if(StringUtils.isNotBlank(peccancyInformation.getTenantId())){
            queryWrapper.eq(PeccancyInformation::getTenantId, peccancyInformation.getTenantId());
        }
        if(StringUtils.isNotBlank(peccancyInformation.getStatus())){
            if(peccancyInformation.getStatus().indexOf(StringPool.COMMA)>-1){
                List<String> statusList = Arrays.asList(peccancyInformation.getStatus().split(StringPool.COMMA));
                queryWrapper.in(PeccancyInformation::getStatus, statusList);
            }else {
                queryWrapper.eq(PeccancyInformation::getStatus, peccancyInformation.getStatus());
            }

        }
        if(StringUtils.isNotBlank(peccancyInformation.getProjectName())){
            queryWrapper.like(PeccancyInformation::getProjectName, peccancyInformation.getProjectName());
        }
        if(StringUtils.isNotBlank(peccancyInformation.getPeccancyRealName())){
            queryWrapper.like(PeccancyInformation::getPeccancyRealName, peccancyInformation.getPeccancyRealName());
        }
        if(StringUtils.isNotBlank(peccancyInformation.getPeccancyUserDeptId())){
            queryWrapper.eq(PeccancyInformation::getPeccancyUserDeptId, peccancyInformation.getPeccancyUserDeptId());
        }
        if(StringUtils.isNotBlank(peccancyInformation.getInvoiceUserId())){
            queryWrapper.eq(PeccancyInformation::getInvoiceUserId, peccancyInformation.getInvoiceUserId());
        }

        if(peccancyInformation.getStartDate() !=null && peccancyInformation.getEndDate() != null ){
            queryWrapper.between(PeccancyInformation::getPeccancyTime, peccancyInformation.getStartDate(),peccancyInformation.getEndDate());
        }

        if(StringUtils.isNotBlank(peccancyInformation.getPenaltyAmountStatus())){
            queryWrapper.eq(PeccancyInformation::getPenaltyAmountStatus, peccancyInformation.getPenaltyAmountStatus());
        }
        queryWrapper.orderByDesc(PeccancyInformation::getCreatedTime);

        Page<PeccancyInformation> page = new Page<>(request.getPageNum(), request.getPageSize());
        FebsUtil.pageWrapper(page, request);
        return this.page(page, queryWrapper);
    }

    @Override
    public IPage<PeccancyInformationDto> findPeccancyInformationDtoPage(QueryRequest request, PeccancyInformationQueryDto peccancyInformation) {
        IPage<PeccancyInformation> page = this.findPeccancyInformationPage(request,peccancyInformation);
        List<PeccancyInformation> informationList = page.getRecords();
        List<PeccancyInformationDto> informationDtoList = BeanHelper.copyWithCollection(informationList,PeccancyInformationDto.class);
        IPage<PeccancyInformationDto> resultPage = new Page<>();
        resultPage.setTotal(page.getTotal());
        resultPage.setRecords(informationDtoList);
        return resultPage;
    }

    /**
     * 查询（所有）
     * @author wanghw
     * @date 2024-08-12 09:46:29
     * @param peccancyInformation peccancyInformation
     * @return List<PeccancyInformation>
     */
    @Override
    public List<PeccancyInformation> findPeccancyInformationList(PeccancyInformation peccancyInformation) {
	    LambdaQueryWrapper<PeccancyInformation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PeccancyInformation::getDeletedFlg, 0);
		// TODO 设置查询条件
		return this.baseMapper.selectList(queryWrapper);
    }

    /**
    * 根据ID查询
    * @author wanghw
    * @date 2024-08-12 09:46:29
    * @param id
    * @return PeccancyInformation
    */
    @Override
    public PeccancyInformation findPeccancyInformationById(String id){
        return this.baseMapper.selectById(id);
    }

    @Override
    public PeccancyInformationDto findPeccancyInformationDtoById(String id) {
        PeccancyInformation information = this.baseMapper.selectById(id);
        PeccancyInformationDto dto = new PeccancyInformationDto();
        if(ObjectUtils.isNotEmpty(information)){
            BeanUtils.copyProperties(information,dto);
            PeccancyInformationFile queryFile = new PeccancyInformationFile();
            queryFile.setInformationId(information.getInformationId());
            List<PeccancyInformationFile> fileList = peccancyInformationFileService.findPeccancyInformationFileList(queryFile);
            dto.setFileList(fileList);
            Tenant tenant = tenantService.findTenantByTenantId(information.getTenantId());
            dto.setTenantName(tenant.getTenantName());

            PeccancyAuditRecord queryRecord = new PeccancyAuditRecord();
            queryRecord.setInformationId(information.getInformationId());
            queryRecord.setAuditBusiness(PeccancyConstant.AUDIT_BUSINESS.AUDIT);
            List<PeccancyAuditRecord> auditList = auditRecordService.findPeccancyAuditRecordList(queryRecord);
            dto.setAuditList(auditList);

            queryRecord.setAuditBusiness(PeccancyConstant.AUDIT_BUSINESS.ISSUANCE);
            List<PeccancyAuditRecord> inssuanceList = auditRecordService.findPeccancyAuditRecordList(queryRecord);
            dto.setIssuanceList(inssuanceList);

        }
        return dto;
    }

    /**
     * 新增
     * @author wanghw
     * @date 2024-08-12 09:46:29
     * @param peccancyInformation peccancyInformation
     */
    @Override
    @Transactional
    public void createPeccancyInformation(PeccancyInformationDto peccancyInformation) throws FebsException{
        peccancyInformation.setCreatedTime(new Date());
        this.save(peccancyInformation);
        List<PeccancyInformationFile> fileList = peccancyInformation.getFileList();
        fileList.forEach(item->{
            item.setTenantId(peccancyInformation.getTenantId());
            item.setInformationId(peccancyInformation.getInformationId());
            item.setCreatedBy(peccancyInformation.getCreatedBy());
            item.setDeletedFlg(FebsConstant.VALID);
            item.setCreatedTime(new Date());
        });
        peccancyInformationFileService.saveBatch(fileList);

        if(PeccancyConstant.INFORMATION_STATUS.WAITING_ISSUANCE.equals(peccancyInformation.getStatus()) ||
                PeccancyConstant.INFORMATION_STATUS.ISSUANCED.equals(peccancyInformation.getStatus())){
            //自动审核完成
            PeccancyAuditRecord auditRecord = setAuditRecord(peccancyInformation);
            auditRecordService.createPeccancyAuditRecord(auditRecord);
        }

        if(PeccancyConstant.INFORMATION_STATUS.ISSUANCED.equals(peccancyInformation.getStatus())){
            //自动审核完成
            PeccancyAuditRecord issuanceRecord = setIssuanceRecord(peccancyInformation);
            auditRecordService.createPeccancyAuditRecord(issuanceRecord);
        }
        saveOrUpdateApply(peccancyInformation);
    }

    /**
     * 修改
     * @author wanghw
     * @date 2024-08-12 09:46:29
     * @param peccancyInformation peccancyInformation
     */
    @Override
    @Transactional
    public void updatePeccancyInformation(PeccancyInformation peccancyInformation) {
        peccancyInformation.setUpdatedTime(new Date());
        this.saveOrUpdate(peccancyInformation);
    }

    @Override
    public void updatePeccancyInformationDto(PeccancyInformationDto peccancyInformation) throws FebsException{
        this.updatePeccancyInformation(peccancyInformation);
        peccancyInformationFileService.update(new LambdaUpdateWrapper<PeccancyInformationFile>()
                .eq(PeccancyInformationFile::getInformationId,peccancyInformation.getInformationId())
                .set(PeccancyInformationFile::getDeletedFlg,FebsConstant.INVALID)
                .set(PeccancyInformationFile::getDeletedTime,new Date())
                .set(PeccancyInformationFile::getDeletedBy,peccancyInformation.getUpdatedBy()));
        List<PeccancyInformationFile> fileList = peccancyInformation.getFileList();
        fileList.forEach(item->{
            item.setTenantId(peccancyInformation.getTenantId());
            item.setInformationId(peccancyInformation.getInformationId());
            item.setCreatedBy(peccancyInformation.getUpdatedBy());
            item.setDeletedFlg(FebsConstant.VALID);
            item.setCreatedTime(new Date());
        });
        peccancyInformationFileService.saveBatch(fileList);

        if(PeccancyConstant.INFORMATION_STATUS.WAITING_ISSUANCE.equals(peccancyInformation.getStatus()) ||
                PeccancyConstant.INFORMATION_STATUS.ISSUANCED.equals(peccancyInformation.getStatus())){
            //自动审核完成
            PeccancyAuditRecord auditRecord = setAuditRecord(peccancyInformation);
            auditRecordService.createPeccancyAuditRecord(auditRecord);
        }

        if(PeccancyConstant.INFORMATION_STATUS.ISSUANCED.equals(peccancyInformation.getStatus())){
            //自动审核完成
            PeccancyAuditRecord issuanceRecord = setIssuanceRecord(peccancyInformation);
            auditRecordService.createPeccancyAuditRecord(issuanceRecord);
        }
        saveOrUpdateApply(peccancyInformation);
    }


    /**
     * 审核违章记录
     * @param peccancyInformation
     * @throws FebsException
     */
    @Override
    public void auditPeccancyInformation(PeccancyInformation peccancyInformation,String oriStatus) throws FebsException {
        LambdaUpdateWrapper<PeccancyInformation> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(PeccancyInformation::getInformationId,peccancyInformation.getInformationId());
        updateWrapper.eq(PeccancyInformation::getDeletedFlg,FebsConstant.VALID);
        updateWrapper.eq(PeccancyInformation::getStatus, oriStatus);
        int updateRow = this.baseMapper.update(peccancyInformation,updateWrapper);
        if(updateRow == 1){
            User user = (User) SecurityUtils.getSubject().getPrincipal();
            //审核记录表增加审核记录
            peccancyInformation.setAuditUserId(user.getUserId());
            peccancyInformation.setAuditRealName(user.getUname());
            peccancyInformation.setAuditDate(new Date());
            PeccancyAuditRecord auditRecord = setAuditRecord(peccancyInformation);
            auditRecordService.createPeccancyAuditRecord(auditRecord);

            if(PeccancyConstant.INFORMATION_STATUS.ISSUANCED.equals(peccancyInformation.getStatus())){
                //自动审核完成
                PeccancyAuditRecord issuanceRecord = setIssuanceRecord(peccancyInformation);
                auditRecordService.createPeccancyAuditRecord(issuanceRecord);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void issuancePeccancyInformation(PeccancyInformation peccancyInformation) throws FebsException {
        LambdaUpdateWrapper<PeccancyInformation> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(PeccancyInformation::getInformationId,peccancyInformation.getInformationId());
        updateWrapper.eq(PeccancyInformation::getDeletedFlg,FebsConstant.VALID);
        updateWrapper.eq(PeccancyInformation::getStatus,PeccancyConstant.INFORMATION_STATUS.WAITING_ISSUANCE);
        int updateRow = this.baseMapper.update(peccancyInformation,updateWrapper);
        if(updateRow == 1){
            //审核记录表增加签发记录
            PeccancyAuditRecord issuanceRecord = setIssuanceRecord(peccancyInformation);
            auditRecordService.createPeccancyAuditRecord(issuanceRecord);

            //审核记录表增加审核记录
            PeccancyInformation resultInformation = this.findPeccancyInformationById(peccancyInformation.getInformationId());
            if(PeccancyConstant.INFORMATION_STATUS.ISSUANCED.equals(resultInformation.getStatus())
                    && PeccancyConstant.IS_OR_NO.IS.equals(resultInformation.getPenaltyScoreFlg())
                    && PeccancyConstant.isUser(resultInformation.getPeccancyObject())){
                // 扣积分，插记录

                if(StringUtils.isBlank(resultInformation.getPeccancyUserId())){
                    throw new FebsException("违章人员id为空");
                }
                if(Objects.isNull(resultInformation.getPenaltyScore())){
                    throw new FebsException("罚款分数不能为空");
                }
                User byId = userService.findById(resultInformation.getPeccancyUserId());
                if(null != byId) {
                    // 减用户积分
                    User u = new User();
                    u.setUpdatedBy(resultInformation.getUpdatedBy());
                    u.setModifyTime(new Date());
                    u.setTotalScore(resultInformation.getPenaltyScore().intValue());
                    u.setUserId(resultInformation.getPeccancyUserId());
                    boolean success = userService.updateScore(u);
                    if (!success) {
                        throw new FebsException("【" + u.getUserName() + "】用户积分更新失败，请联系管理员！");
                    }

                    // 用户积分使用记录
                    BaseUserScoreRecord baseUserScoreRecord = new BaseUserScoreRecord();
                    baseUserScoreRecord.setTenantId(resultInformation.getTenantId());
                    baseUserScoreRecord.setUserId(resultInformation.getPeccancyUserId());
                    baseUserScoreRecord.setRealName(resultInformation.getPeccancyRealName());
                    baseUserScoreRecord.setUserNo(resultInformation.getPeccancyUserNo());
                    baseUserScoreRecord.setDeptId(resultInformation.getPeccancyUserDeptId());
                    baseUserScoreRecord.setDeptName(resultInformation.getPeccancyUserDept());
                    baseUserScoreRecord.setDataSource("2");
                    baseUserScoreRecord.setDataTargetId(resultInformation.getInformationId());
                    baseUserScoreRecord.setOperateType("2");
                    baseUserScoreRecord.setOperateDate(new Date());
                    baseUserScoreRecord.setOperateScore(resultInformation.getPenaltyScore().intValue());
                    baseUserScoreRecord.setBeforeScore(byId.getTotalScore() ==null ? 0: byId.getTotalScore());
                    baseUserScoreRecord.setAfterScore((byId.getTotalScore() ==null ? 0: byId.getTotalScore())- resultInformation.getPenaltyScore().intValue());
                    baseUserScoreRecord.setCreatedBy(resultInformation.getUpdatedBy());
                    baseUserScoreRecord.setCreatedTime(new Date());
                    boolean save1 = baseUserScoreRecordService.save(baseUserScoreRecord);
                    if (!save1) {
                        throw new FebsException("用户积分使用记录更新失败，请联系管理员！");
                    }
                }
            }
        }


    }

    /**
     * 线下支付
     * @param peccancyInformation
     */
    @Override
    public void informationOffLinePay(PeccancyInformation peccancyInformation) {
        LambdaUpdateWrapper<PeccancyInformation> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(PeccancyInformation::getInformationId,peccancyInformation.getInformationId());
        updateWrapper.eq(PeccancyInformation::getDeletedFlg,FebsConstant.VALID);
        updateWrapper.eq(PeccancyInformation::getPenaltyAmountStatus,PeccancyConstant.IS_OR_NO.NO);
        this.baseMapper.update(peccancyInformation,updateWrapper);
    }


    /**
     * 逻辑删除
     * @author wanghw
     * @date 2024-08-12 09:46:29
     * @param peccancyInformation peccancyInformation
     * @param peccancyInformationIds peccancyInformationIds
     */
    @Override
    @Transactional
    public void deletePeccancyInformation(PeccancyInformation peccancyInformation,String peccancyInformationIds) {
        List<String> list = Arrays.asList(peccancyInformationIds.split(StringPool.COMMA));
        this.baseMapper.update(peccancyInformation,new LambdaQueryWrapper<PeccancyInformation>().in(PeccancyInformation::getInformationId,list));
        peccancyInformationFileService.update(new LambdaUpdateWrapper<PeccancyInformationFile>()
                .eq(PeccancyInformationFile::getInformationId,peccancyInformationIds)
                .set(PeccancyInformationFile::getDeletedFlg,FebsConstant.INVALID)
                .set(PeccancyInformationFile::getDeletedTime,new Date())
                .set(PeccancyInformationFile::getDeletedBy,peccancyInformation.getDeletedBy()));
	}

    /**
    * 物理删除
    * @author wanghw
    * @date 2024-08-12 09:46:29
    * @param peccancyInformationIds peccancyInformationIds
    */
    @Override
    @Transactional
    public void physicallyDeletePeccancyInformation(String peccancyInformationIds) {
        List<String> list = Arrays.asList(peccancyInformationIds.split(StringPool.COMMA));
        LambdaQueryWrapper<PeccancyInformation> wapper = new LambdaQueryWrapper<>();
        wapper.in(PeccancyInformation::getInformationId,list);
        this.remove(wapper);
    }

    @Override
    @Transactional
    public String createPeccancyNo(String tenantId,String deptId) {
        StringBuilder no =  new StringBuilder();
        Tenant tenant = tenantService.getById(tenantId);
        if(ObjectUtils.isNotEmpty(tenant) && StringUtils.isNotBlank(tenant.getBusinessCode())){
            no.append(tenant.getBusinessCode());
        }
        Dept dept = deptService.findDeptByDeptId(deptId);
        if(ObjectUtils.isNotEmpty(dept)  && StringUtils.isNotBlank(dept.getBusinessCode()) ){
            no.append(dept.getBusinessCode());
        }
        PeccancyInformation information = this.baseMapper.selectOne(
                new LambdaQueryWrapper<PeccancyInformation>()
                        .ge(PeccancyInformation::getCreatedTime,DateUtil.getCurrentYuanDan())
                        .orderByDesc(PeccancyInformation::getCreatedTime).last("limit 1"));
        no.append(Calendar.getInstance().get(Calendar.YEAR)%2000);
        if(null != information){
            //在最新的编号上+1
            String currentNewestNo = information.getPeccancyNo().substring(information.getPeccancyNo().length()-5,information.getPeccancyNo().length());
            no.append(String.format("%05d",Integer.parseInt(currentNewestNo)+1));
        }else{
            //创建该公司下第一个事故编号
            no.append(PeccancyConstant.PECCANCY_NO_START_NUM);
        }
        return no.toString();
    }

    /**
     * 统计本年度 审核通过的 该人员的 违章次数，罚款金额以及扣除分数
     *
     * @return
     */
    @Override
    public Map<String, Object> countPeccancyByUserId(PeccancyInformationDto peccancyInformation) {
        if(ObjectUtils.isEmpty(peccancyInformation)){
            return null;
        }
        QueryWrapper<PeccancyInformation> wrapper = new QueryWrapper<>();
        wrapper.select("count(1) as yearCount",
                "CASE WHEN SUM(penalty_amount)>0 THEN SUM(penalty_amount) ELSE '0' end as amountCount",
                "CASE WHEN SUM(penalty_score)>0 THEN SUM(penalty_score) ELSE '0' end as scoreCount",
                "CASE WHEN SUM(learn_video_flg)>0 THEN SUM(learn_video_flg) ELSE '0' end as videoCount");
        if(PeccancyConstant.USE_SCOPE.CONTRACTOR.equals(peccancyInformation.getPeccancyObject())){
            wrapper.eq("peccancy_user_contractor_team_id",peccancyInformation.getPeccancyUserContractorTeamId());
        }else  if(PeccancyConstant.USE_SCOPE.DEPT.equals(peccancyInformation.getPeccancyObject())){
            wrapper.eq("peccancy_user_dept_id",peccancyInformation.getPeccancyUserDeptId());
        }else {
            wrapper.eq("peccancy_user_id",peccancyInformation.getPeccancyUserId());
        }


        List<String> statusList = Arrays.asList(PeccancyConstant.INFORMATION_STATUS.WAITING_ISSUANCE,
                PeccancyConstant.INFORMATION_STATUS.ISSUANCE_FAIL,
                PeccancyConstant.INFORMATION_STATUS.ISSUANCED);
        wrapper.in("status",statusList);
        wrapper.eq("peccancy_object",peccancyInformation.getPeccancyObject());
        wrapper.ge("peccancy_time", DateUtil.getCurrentYuanDan());
        return this.getMap(wrapper);
    }

    /**
     * 统计某开单人，当年总计开单罚款金额，罚款积分
     *
     * @param inVoiceuserId
     * @return
     */
    @Override
    public Map<String, Object> countPeccancyByInvoiceUserId(String inVoiceuserId) {
        if(StringUtils.isBlank(inVoiceuserId)){
            return null;
        }
        QueryWrapper<PeccancyInformation> wrapper = new QueryWrapper<>();
        wrapper.select("CASE WHEN SUM(penalty_amount)>0 THEN SUM(penalty_amount) ELSE '0' end as amountCount",
                "CASE WHEN SUM(penalty_score)>0 THEN SUM(penalty_score) ELSE '0' end as scoreCount");
        wrapper.eq("invoice_user_id",inVoiceuserId);
        List<String> statusList = Arrays.asList(PeccancyConstant.INFORMATION_STATUS.WAITING_ISSUANCE,
                PeccancyConstant.INFORMATION_STATUS.ISSUANCE_FAIL,
                PeccancyConstant.INFORMATION_STATUS.ISSUANCED);
        wrapper.in("status",statusList);
        wrapper.ge("peccancy_time", DateUtil.getCurrentYuanDan());
        return this.getMap(wrapper);
    }

    private PeccancyAuditRecord setAuditRecord(PeccancyInformation peccancyInformation){
        //审核记录表增加审核记录
        PeccancyAuditRecord auditRecord = new PeccancyAuditRecord();
        auditRecord.setInformationId(peccancyInformation.getInformationId());
        auditRecord.setTenantId(peccancyInformation.getTenantId());
        auditRecord.setAuditUserId(peccancyInformation.getAuditUserId());
        auditRecord.setAuditRealName(peccancyInformation.getAuditRealName());
        if(PeccancyConstant.INFORMATION_STATUS.WAITING_ISSUANCE.equals(peccancyInformation.getStatus())
                || PeccancyConstant.INFORMATION_STATUS.ISSUANCED.equals(peccancyInformation.getStatus())){
            auditRecord.setAuditResult(PeccancyConstant.IS_OR_NO.IS);
        }else {
            auditRecord.setAuditResult(PeccancyConstant.IS_OR_NO.NO);
        }
        auditRecord.setAuditTime(new Date());
        auditRecord.setPeccancyNature(peccancyInformation.getPeccancyNature());
        auditRecord.setAuditBusiness(PeccancyConstant.AUDIT_BUSINESS.AUDIT);
        auditRecord.setAuditReason(peccancyInformation.getAuditRemark());
        auditRecord.setCreatedTime(new Date());
        auditRecord.setCreatedBy(peccancyInformation.getUpdatedBy());
        return auditRecord;
    }


    private PeccancyAuditRecord setIssuanceRecord(PeccancyInformation peccancyInformation){
        //审核记录表增加签发记录
        PeccancyAuditRecord issuanceRecord = new PeccancyAuditRecord();
        issuanceRecord.setInformationId(peccancyInformation.getInformationId());
        issuanceRecord.setTenantId(peccancyInformation.getTenantId());
        issuanceRecord.setAuditUserId(peccancyInformation.getIssuanceUserId());
        issuanceRecord.setAuditRealName(peccancyInformation.getIssuanceRealName());
        if(PeccancyConstant.INFORMATION_STATUS.ISSUANCED.equals(peccancyInformation.getStatus())){
            issuanceRecord.setAuditResult(PeccancyConstant.IS_OR_NO.IS);
        }else {
            issuanceRecord.setAuditResult(PeccancyConstant.IS_OR_NO.NO);
        }
        issuanceRecord.setAuditTime(new Date());
        issuanceRecord.setPeccancyNature(peccancyInformation.getPeccancyNature());
        issuanceRecord.setAuditBusiness(PeccancyConstant.AUDIT_BUSINESS.ISSUANCE);
        issuanceRecord.setAuditReason(peccancyInformation.getIssuanceRemark());
        issuanceRecord.setCreatedTime(new Date());
        issuanceRecord.setCreatedBy(peccancyInformation.getUpdatedBy());
        return issuanceRecord;
    }

    private void saveOrUpdateApply(PeccancyInformationDto peccancyInformation) throws FebsException {
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        LambdaQueryWrapper<WorkflowApply> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(WorkflowApply::getWorkflowApplyId, peccancyInformation.getWorkflowApplyId());
        lambdaQueryWrapper.eq(WorkflowApply::getDeletedFlg, "0");
        WorkflowApply workflowApply = workflowApplyService.getOne(lambdaQueryWrapper);
        //判断当前模块的审核配置是否开启
        LambdaQueryWrapper<PeccancyModuleConfig> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PeccancyModuleConfig::getDeletedFlg, "0");
        queryWrapper.eq(PeccancyModuleConfig::getTenantId, peccancyInformation.getTenantId());
        queryWrapper.last("limit 1");
        PeccancyModuleConfig moduleConfigServiceOne = peccancyModuleConfigService.getOne(queryWrapper);
        //审核开启开启且整改审核方式是流程审核
        if (null != moduleConfigServiceOne && ("1").equals(moduleConfigServiceOne.getReviewSwitch()) && ("2").equals(moduleConfigServiceOne.getReviewType())) {
            //查询流程信息表
            LambdaQueryWrapper<WorkflowInfo> wrapper = new LambdaQueryWrapper();
            wrapper.eq(WorkflowInfo::getWorkflowBusiness, "3");
            wrapper.eq(WorkflowInfo::getTenantId, peccancyInformation.getTenantId());
            wrapper.last("limit 1");
            WorkflowInfo workflowInfo = workflowInfoService.getOne(wrapper);

            WorkflowApply newWorkflowApply = new WorkflowApply();
            //流程信息不为空
            if (null != workflowInfo) {
                newWorkflowApply.setWorkflowName(workflowInfo.getWorkflowName());
                newWorkflowApply.setWorkflowId(workflowInfo.getWorkflowId());
                newWorkflowApply.setWorkflowBusiness(workflowInfo.getWorkflowBusiness());
            }
            //流程申请不为空
            if (null != workflowApply) {
                newWorkflowApply.setWorkflowApplyId(workflowApply.getWorkflowApplyId());
            }
            newWorkflowApply.setBusinessId(peccancyInformation.getInformationId());
            newWorkflowApply.setTenantId(peccancyInformation.getTenantId());
            if (("1").equals(peccancyInformation.getStatus())) {//待提交
                newWorkflowApply.setWorkflowApplyStatus("1");
            } else if (("2").equals(peccancyInformation.getStatus())) {//待审核
                newWorkflowApply.setWorkflowApplyStatus("2");
            }
            //插入审核流程
            String applyId = workflowApplyService.saveWorkflowApply(newWorkflowApply, user.getUserName(), user.getUname());
            //数据回填
            if(null==workflowApply){
                LambdaUpdateWrapper<PeccancyInformation> updateWrapper=new LambdaUpdateWrapper<>();
                updateWrapper.set(PeccancyInformation::getWorkflowApplyId,applyId);
                updateWrapper.set(PeccancyInformation::getUpdatedBy,user.getUserName());
                updateWrapper.set(PeccancyInformation::getUpdatedTime,new Date());
                updateWrapper.eq(PeccancyInformation::getInformationId,peccancyInformation.getInformationId());
                this.update(updateWrapper);
            }
        }else{
            if(null != workflowApply){
                throw new FebsException("当前对应的审核流程已关闭！");
            }
        }
    }
}
